#include "calServer.hpp"
#include "protocol.hpp"
#include <iostream>
#include <memory>

static void Usage(string str)
{
    cout << "Usage: " << str << " local_port" << endl;
}

enum
{
    DIV_ERR = 1,
    MOD_ERR,
    OP_ERR
};

void cal(const Request &req, Response &resp)
{
    resp.flag = 0;
    resp.result = 0;
    switch (req.op)
    {
    case '+':
        resp.result = req.x + req.y;
        break;
    case '-':
        resp.result = req.x - req.y;
        break;
    case '*':
        resp.result = req.x * req.y;
        break;
    case '/':
    {
        if (req.y == 0)
            resp.flag = DIV_ERR;
        else
            resp.result = req.x / req.y;
    }
    break;
    case '%':
    {
        if (req.y == 0)
            resp.flag = MOD_ERR;
        else
            resp.result = req.x % req.y;
    }
    break;
    default:
        resp.flag = OP_ERR;
        break;
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t port = atoi(argv[1]);
    unique_ptr<Server> svr(new Server(port, cal));
    svr->initServer();
    svr->start();

    return 0;
}
